# 为Redis设置密码的PowerShell脚本
Write-Host "Setting Redis password..." -ForegroundColor Yellow

try {
    $socket = New-Object System.Net.Sockets.TcpClient
    $socket.Connect("127.0.0.1", 6379)
    
    if ($socket.Connected) {
        Write-Host "✓ Connected to Redis" -ForegroundColor Green
        
        $stream = $socket.GetStream()
        
        # 设置密码命令
        $password = "RedisData@123456."
        $configCommand = "*3`r`n`$6`r`nCONFIG`r`n`$3`r`nSET`r`n`$11`r`nrequirepass`r`n`$" + $password.Length + "`r`n" + $password + "`r`n"
        $configBytes = [System.Text.Encoding]::ASCII.GetBytes($configCommand)
        $stream.Write($configBytes, 0, $configBytes.Length)
        
        # 读取响应
        $buffer = New-Object byte[] 1024
        $response = $stream.Read($buffer, 0, 1024)
        $responseText = [System.Text.Encoding]::ASCII.GetString($buffer, 0, $response)
        
        Write-Host "CONFIG SET response: $($responseText.Trim())" -ForegroundColor Cyan
        
        if ($responseText.Contains("+OK")) {
            Write-Host "✓ Password set successfully!" -ForegroundColor Green
            Write-Host "Redis password is now: $password" -ForegroundColor Yellow
            
            # 保存配置到磁盘
            $saveCommand = "*1`r`n`$11`r`nCONFIG REWRITE`r`n"
            $saveBytes = [System.Text.Encoding]::ASCII.GetBytes($saveCommand)
            $stream.Write($saveBytes, 0, $saveBytes.Length)
            
            $saveResponse = $stream.Read($buffer, 0, 1024)
            $saveResponseText = [System.Text.Encoding]::ASCII.GetString($buffer, 0, $saveResponse)
            Write-Host "CONFIG REWRITE response: $($saveResponseText.Trim())" -ForegroundColor Cyan
        } else {
            Write-Host "✗ Failed to set password: $($responseText.Trim())" -ForegroundColor Red
        }
        
        $socket.Close()
    }
}
catch {
    Write-Host "✗ Error: $($_.Exception.Message)" -ForegroundColor Red
}

Write-Host "`nNote: After setting the password, you may need to restart Redis service for persistent effect." -ForegroundColor Yellow 